package com.liqi.quartz.task;

import com.alibaba.druid.support.json.JSONUtils;
import com.liqi.common.utils.DateUtils;
import com.liqi.deployment.domain.DvDeployment;
import com.liqi.deployment.domain.DvOperationUser;
import com.liqi.deployment.service.IDvDeploymentService;
import com.liqi.monitor.domain.DvDeploymentSystem;
import com.liqi.monitor.service.IDvDeploymentSystemService;
import com.liqi.sms.domain.SysShortMessage;
import com.liqi.sms.service.ISysShortMessageService;
import com.liqi.system.domain.SysMail;
import com.liqi.system.service.IMailService;
import com.liqi.system.service.ISysConfigService;
import com.liqi.system.service.ISysMailService;
import com.liqi.system.service.device.IDvOperationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component("morningTask")
public class MorningTask {
    @Autowired
    private IMailService mailService;

    @Autowired
    private ISysMailService SysMailService;

    @Autowired
    private IDvDeploymentSystemService dvDeploymentSystemService;

    @Autowired
    private IDvOperationUserService dvOperationUserService;

    @Autowired
    private IDvDeploymentService deploymentService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysShortMessageService sysShortMessageService;

    private String configKey = "heartbeat";//配置名称

    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.CarbonCopy}")
    private String CarbonCopy;

    public void morningUp(){
        System.out.println("morning get up everyday!!!");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<DvDeploymentSystem> list = dvDeploymentSystemService.selectDvEquipmentSystemForTask();
        for (DvDeploymentSystem dvEquipmentStatusLog : list) {
            Date updateTime = dvEquipmentStatusLog.getUpdateTime();//获取心跳表更新时间
            String deviceId = dvEquipmentStatusLog.getDeviceId();
            DvDeployment dvDeployment = deploymentService.selectDvDeploymentByDeviceId(deviceId);//获取投放设备
            
            //设备状态日志对象的更新时间不为空
            if (updateTime != null) {
                Calendar beforeTime = Calendar.getInstance();
                String configValue = sysConfigService.selectConfigByKey(configKey);//获取配置的心跳间隔时间
                int amount = Integer.parseInt(configValue);
                beforeTime.add(Calendar.MINUTE, -amount);// 5分钟之前的时间
                Date beforeDate = beforeTime.getTime();
                boolean before = updateTime.before(beforeDate); //更新时间是否早于 5分钟之前
                //如果更新时间早于当前时间的5分钟之前
                if (before) {
                    if (dvDeployment != null) {
                        // 设备状态，0是正常，1是离线，2是当天异常
                        String deviceStatus = dvDeployment.getDeviceStatus();
                        String operationUserCode = dvDeployment.getOperationUserCode();
                        DvOperationUser dvOperationUser = dvOperationUserService.selectDvOperationUserByCode(operationUserCode);
                        String email = null;
                        String operationUserName = null;
                        if (null != dvOperationUser) {
                            email = dvOperationUser.getEmail();
                        }
                        SysMail sysMail = new SysMail();
                        sysMail.setMailFrom(from);
                        sysMail.setMailToList(email);
                        sysMail.setSubject(dvDeployment.getDeploymentName() + "设备异常，需要尽快修理！！！！！");
                        Map<String,Object> map = new HashMap<>();
                        map.put("operationUserName", dvDeployment.getOperationUserName());
                        map.put("nowTime",df.format(new Date()));
                        map.put("deviceId",deviceId);
                        map.put("deploymentName", dvDeployment.getDeploymentName());
                        map.put("deploymentAddress", dvDeployment.getAncestorsName()+ dvDeployment.getDeploymentAddress());
                        map.put("errorInfo","机器目前处于离线状态，尽快开机检测");
                        map.put("reportType","心跳上报");
                        String result = JSONUtils.toJSONString(map);
                        sysMail.setBody(result);
                        sysMail.setCcList(CarbonCopy);
                        sysMail.setCreateBy("心跳上报");
                        sysMail.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));
                        SysMailService.insertSysMail(sysMail);

                        // 新建短信实体，并插入到短信实体数据库
                        SysShortMessage sysShortMessage = new SysShortMessage();
                        sysShortMessage.setPhoneNumbers(dvOperationUser.getPhoneNumber());
                        sysShortMessage.setCreateBy("心跳上报");
                        sysShortMessage.setCreateTime(DateUtils.getNowDate());
                        sysShortMessage.setSendFlag("0");
                        sysShortMessage.setTemplateParam(result);
                        sysShortMessageService.insertSysShortMessage(sysShortMessage);

                        try {
                            mailService.sendTemplateMailByDevice(sysMail);
                            sysMail.setSendFlag("3");
                            sysMail.setSendTime(new java.sql.Date(new java.util.Date().getTime()));
                            sysMail.setUpdateBy("心跳定时任务发送邮件成功");
                            SysMailService.updateSysMail(sysMail);
                        }catch (Exception e){
                                e.printStackTrace();
                                sysMail.setSendInfo(e.getMessage());
                                sysMail.setSendFlag("6");
                                sysMail.setUpdateBy("心跳定时任务发送邮件失败");
                                SysMailService.updateSysMail(sysMail);
                        }

                    }
                }
            }
            //设备状态日志对象的更新时间为空   .
            else {
                if (dvDeployment != null) {
                    // 设备状态，0是正常，1是离线，2是当天异常
                    String deviceStatus = dvDeployment.getDeviceStatus();
                    String operationUserCode = dvDeployment.getOperationUserCode();
                    DvOperationUser dvOperationUser = dvOperationUserService.selectDvOperationUserByCode(operationUserCode);
                    String email = null;
                    String operationUserName = null;
                    if (null != dvOperationUser) {
                        email = dvOperationUser.getEmail();
                    }
                    SysMail sysMail = new SysMail();
                    sysMail.setMailToList(email);
                    sysMail.setMailFrom(from);
                    sysMail.setSubject(dvDeployment.getDeploymentName() + "设备异常，需要尽快修理！！！！！");
                    Map<String,Object> map = new HashMap<>();
                    map.put("operationUserName", dvDeployment.getOperationUserName());
                    map.put("nowTime",df.format(new Date()));
                    map.put("deviceId",deviceId);
                    map.put("deploymentName", dvDeployment.getDeploymentName());
                    map.put("deploymentAddress", dvDeployment.getAncestorsName()+ dvDeployment.getDeploymentAddress());
                    map.put("errorInfo","机器目前处于离线状态，尽快开机检测");
                    map.put("reportType","心跳上报");
                    String result = JSONUtils.toJSONString(map);
                    sysMail.setBody(result);
                    sysMail.setCcList(CarbonCopy);
                    sysMail.setCreateBy("心跳上报");
                    sysMail.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));
                    SysMailService.insertSysMail(sysMail);

                    // 新建短信实体，并插入到短信实体数据库
                    SysShortMessage sysShortMessage = new SysShortMessage();
                    sysShortMessage.setPhoneNumbers(dvOperationUser.getPhoneNumber());
                    sysShortMessage.setCreateBy("心跳上报");
                    sysShortMessage.setCreateTime(DateUtils.getNowDate());
                    sysShortMessage.setSendFlag("0");
                    sysShortMessage.setTemplateParam(result);
                    sysShortMessageService.insertSysShortMessage(sysShortMessage);

                    try {
                        mailService.sendTemplateMailByDevice(sysMail);
                        sysMail.setSendFlag("3");
                        sysMail.setSendTime(new java.sql.Date(new java.util.Date().getTime()));
                        sysMail.setUpdateBy("心跳定时任务发送邮件成功");
                        SysMailService.updateSysMail(sysMail);
                    }catch (Exception e){
                        e.printStackTrace();
                        sysMail.setSendInfo(e.getMessage());
                        sysMail.setSendFlag("6");
                        sysMail.setUpdateBy("心跳定时任务发送邮件失败");
                        SysMailService.updateSysMail(sysMail);
                    }

                }
            }
        }
    }

}
